import React, { Component, Fragment } from 'react';
import {
  Button,
  Card,
  Descriptions,
  Form,
  Icon,
  InputNumber,
  Drawer,
  Popconfirm,
  Select,
  Spin,
  Tag,
  Upload,
  Divider,
} from 'antd';
import styles from './index.less';
import { connect } from 'dva';
import moment from 'moment';
import styled from 'styled-components';
import BaseComponent from '@/components/BaseComponent';
import { njzdImgPrefixUrl } from '@/defaultSettings';
import { PhotoProvider, PhotoView } from 'react-photo-view';
import { DivFooter, LFlexHDiv } from '@/components/MHtmlTag';
import PermissionsWidget from '@/components/PermissionsWidget';

const { Option } = Select;

const InVisibleLabel = styled.span`
  visibility: hidden;
  width: 100px;
`;

const UploadHintText = styled.span`
  font-size: 12px;
  color: #e43c2e;
`;

const ThumbnailBox = styled.div`
  display: flex;
  align-items: center;
  margin-top: 8px;

  .thumbnailImage {
    width: 60px;
    height: 60px;
    cursor: pointer;
  }

  .rightPart {
    flex: 1;
    text-align: right;
  }

  .delBtn {
    margin-left: 16px;
  }
`;

const FooterBox = styled.div`
  width: 100%;
  display: flex;
  justify-content: center;
  margin-top: 16px;
`;

const SpinBox = styled.div`
  width: 100%;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
`;

/**
 * 诊疗总量列表
 */
@Form.create()
@connect(({ user, gastroscopestatistics, loading }) => ({
  isPreparing: loading.effects['gastroscopestatistics/findByOrgIdAndUploadYear'],
  isChangIng: loading.effects['gastroscopestatistics/changStatus'],
}))
class DetailView extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      // 是否正在上传
      isUploading: false,
      // 年份数组
      years: [moment().year(), moment().year() - 1, moment().year() - 2],
      // 被选中的年份
      selectedYear: moment().year(),
      // 当前月份
      nowMonth: moment().month() + 1,
      // 数据源
      data: [],
      record: {},
    };
  }

  resetImageUrls = ({ data }) => {
    if (data) {
      // 将数据进行拆分,因为图片可能会有多张
      data.forEach(item => {
        const { envienceFileUrl, envienceFilePath } = item;
        if (envienceFileUrl) {
          // 按照|分割envienceFileUrl
          const envienceFileUrlArr = envienceFileUrl.split('|');
          item.envienceFileUrl = envienceFileUrlArr;
        } else {
          item.envienceFileUrl = [];
        }
        if (envienceFilePath) {
          // 按照|分割envienceFilePath
          const envienceFilePathArr = envienceFilePath.split('|');
          item.envienceFilePath = envienceFilePathArr;
        } else {
          item.envienceFilePath = [];
        }
      });
    }
  };

  /**页面初始化*/
  componentDidMount() {
    const { detailData, record } = this.props;
    this.resetImageUrls({ data: detailData });
    this.setState({
      record: record,
      data: detailData,
      selectedYear: record['upload_year'],
    });
  }

  /**根据主键查看信息*/
  findByOrgIdAndUploadYear = record => {
    const { org_id, upload_year } = record;
    this.execHttp('gastroscopestatistics/findByOrgIdAndUploadYear', {
      orgId: org_id,
      uploadYear: upload_year,
    }).then(resp => {
      const {
        success,
        data: { dataMap },
      } = resp;
      this.resetImageUrls({ data: dataMap });
      this.setState({
        //视图数据
        data: dataMap,
      });
    });
  };

  /**审核信息状态*/
  changStatus = param => {
    this.execHttp('gastroscopestatistics/changStatus', {
      ...param,
    }).then(resp => {
      const { success } = resp;
      if (success) {
        const { record } = this.state;
        this.findByOrgIdAndUploadYear(record);
      }
    });
  };

  render() {
    const { isLoading, visible, onClose, record } = this.props;
    const { selectedYear, years, data } = this.state;
    return (
      <Drawer
        placement="right"
        width={'70%'}
        closable={true}
        onClose={e => {
          if (onClose) {
            onClose(e);
          }
        }}
        visible={visible}
      >
        <div className={styles.totalNumberofClinics}>
          <Card bordered={true} className={styles.contentBox}>
            {isLoading ? (
              <SpinBox>
                <Spin></Spin>
              </SpinBox>
            ) : (
              <>
                {/*基本信息*/}
                <Descriptions bordered title="基本信息" size={'middle'} column={3}>
                  <Descriptions.Item label={<div style={{ width: '100px' }}>机构名称</div>}>
                    <div style={{ width: '150px' }}>{record['org_name']}</div>
                  </Descriptions.Item>
                  <Descriptions.Item label={<div style={{ width: '100px' }}>筛查年度</div>}>
                    <div style={{ width: '250px' }}>
                      <Select
                        defaultValue={selectedYear}
                        style={{ width: '100%' }}
                        onChange={this.handleYearChange}
                      >
                        {years.map((item, index) => {
                          return (
                            <Option value={item} key={index}>
                              {item}
                            </Option>
                          );
                        })}
                      </Select>
                    </div>
                  </Descriptions.Item>
                </Descriptions>
                {/*胃镜总量信息*/}

                <PhotoProvider bannerVisible={false} maskOpacity={0.9}>
                  <Descriptions
                    bordered
                    title="胃镜总量信息"
                    size={'middle'}
                    column={3}
                    style={{ marginTop: '16px' }}
                  >
                    {data.length > 0 ? (
                      data
                        .filter((item, index) => {
                          return index < this.state.nowMonth;
                        })
                        .map((item, index) => {
                          console.log(item, index);
                          return (
                            <Fragment key={index}>
                              <Descriptions.Item
                                label={
                                  <div style={{ width: '100px' }}>{item.uploadMonthText}数量</div>
                                }
                              >
                                <div style={{ width: '150px' }}>
                                  <InputNumber
                                    value={item.count}
                                    disabled={true}
                                    placeholder={'请输入数量'}
                                    style={{ width: '100%' }}
                                  ></InputNumber>
                                </div>
                              </Descriptions.Item>
                              <Descriptions.Item
                                label={
                                  <div style={{ width: '100px' }}>{item.uploadMonthText}佐证</div>
                                }
                              >
                                <div
                                  style={{
                                    display: 'flex',
                                    flexDirection: 'column',
                                  }}
                                >
                                  <div
                                    style={{
                                      display: 'flex',
                                      width: '100%',
                                      flexWrap: 'wrap',
                                    }}
                                  >
                                    {item.envienceFileUrl &&
                                    item.envienceFileUrl.length > 0 &&
                                    Array.isArray(item.envienceFileUrl) ? (
                                      item.envienceFileUrl.map((url, imgIndex) => {
                                        return (
                                          <PhotoView src={`${njzdImgPrefixUrl}${url}`}>
                                            <ThumbnailBox>
                                              <img
                                                className={'thumbnailImage'}
                                                src={`${njzdImgPrefixUrl}${url}`}
                                              />
                                            </ThumbnailBox>
                                          </PhotoView>
                                        );
                                      })
                                    ) : (
                                      <UploadHintText>未上传</UploadHintText>
                                    )}
                                  </div>
                                </div>
                              </Descriptions.Item>
                              <Descriptions.Item
                                label={
                                  <div style={{ width: '80px' }}>
                                    {item.auditStatus == 2 ? (
                                      <Tag color="red">{item.auditStatusCn}</Tag>
                                    ) : null}
                                    {item.auditStatus == 1 ? (
                                      <Tag color="green">{item.auditStatusCn}</Tag>
                                    ) : null}
                                    {item.auditStatus == 0 ? <Tag>{item.auditStatusCn}</Tag> : null}
                                  </div>
                                }
                              >
                                <div>
                                  <PermissionsWidget
                                    tag={'gastroscopetotalstatistics:cer-gastroscope-audit-pass'}
                                  >
                                    <Popconfirm
                                      title="确定执行当前操作吗?"
                                      onConfirm={() => {
                                        this.handleEgisClick(item.id);
                                      }}
                                    >
                                      <Button
                                        style={{
                                          backgroundColor: '#1BA035',
                                          borderColor: '#1BA035',
                                          color: '#FFF',
                                        }}
                                      >
                                        审核通过
                                      </Button>
                                    </Popconfirm>
                                  </PermissionsWidget>
                                  <PermissionsWidget
                                    tag={'gastroscopetotalstatistics:cer-gastroscope-audit-unpass'}
                                  >
                                    <Popconfirm
                                      title="确定执行当前操作吗?"
                                      onConfirm={() => {
                                        this.handleNoEgisClick(item.id);
                                      }}
                                    >
                                      <Button type="danger" style={{ marginLeft: '8px' }}>
                                        审核不通过
                                      </Button>
                                    </Popconfirm>
                                  </PermissionsWidget>
                                </div>
                              </Descriptions.Item>
                            </Fragment>
                          );
                        })
                    ) : (
                      <div>暂无数据</div>
                    )}
                  </Descriptions>
                </PhotoProvider>

                {/*<FooterBox>*/}
                {/*  <Button type={'primary'} onClick={onClose}>*/}
                {/*    关闭*/}
                {/*  </Button>*/}
                {/*</FooterBox>*/}
              </>
            )}
          </Card>
        </div>

        <DivFooter>
          <LFlexHDiv>
            <LFlexHDiv flex={'1'} justifyContent={'center'}>
              <Button
                style={{
                  marginRight: 8,
                  width: '120px',
                }}
                onClick={() => {
                  if (onClose) {
                    onClose();
                  }
                }}
              >
                关闭
              </Button>
            </LFlexHDiv>
          </LFlexHDiv>
        </DivFooter>
      </Drawer>
    );
  }

  /**
   * 筛查年度改变
   * @param value
   */
  handleYearChange = value => {
    this.setState({
      selectedYear: value,
    });
    const record = {
      upload_year: value,
      org_id: '1004799180646469632',
    };
    this.findByOrgIdAndUploadYear(record);
  };

  /**点击审核通过*/
  handleEgisClick = param => {
    if (param !== undefined) {
      const val = {
        status: 1,
        id: param,
      };
      this.changStatus(val);
    }
  };

  /**点击审核不通过*/
  handleNoEgisClick = param => {
    if (param !== undefined) {
      const val = {
        status: 2,
        id: param,
      };
      this.changStatus(val);
    }
  };
}

export default DetailView;
